#coding:utf8

import os
import shutil
import sys
import glob
import codecs
import json
import wave

# def recur_glob(path):
# 	for root, dirs, 

"""
使用说明参数 python 2 环境， 参数一 输入音频路径  参数二输出音频路径  参数三 文本路径  参数四输出文本目录
python xiaomi.py + 各个参数
"""

def move_wav(in_path,out_path):
	wav_dict = {}

	wavs = glob.glob(in_path+'/*.wav')
	for wav in wavs:
		shutil.copy(wav,out_path)
	new_wavs = os.listdir(out_path)

	for new_wav in new_wavs:
		wav_dict[new_wav]=out_path+'/'+new_wav

	print len(new_wavs)
	if len(wav_dict) != len(new_wavs):
		print "has repeate wav "

	return wav_dict


def cal_wav_time(wav):
	try:
		fp = wave.open(wav,'rb')
		wav_time = float(fp.getnframes())/float(fp.getframerate())
		fp.close()
		return wav_time
	except Exception as e:
		print "error wav: "+wav
		raise e


def read_text(path):
	text_dict = {}
	with codecs.open(path,'r',encoding="utf8") as f:
		for line in f:
			line = line.strip().split('\t')
			if len(line)==2:
				wav_name, text_1 = line[0]+'.wav', line[1]
				text_dict[wav_name]=[text_1]
			else:
				print 'has empty line: '+line
				exit()
	return text_dict

def mk_dir(path):
	if not os.path.exists(path):
		os.makedirs(path)
	else:
		pass

def main():
	wav_dict = move_wav(sys.argv[1],sys.argv[2])
	text_dict = read_text(sys.argv[3])
	t_dir_1 = sys.argv[4]+'/1'
	
	mk_dir(t_dir_1)
	
	for k_wav,wav_path in wav_dict.items():
		if text_dict.has_key(k_wav):
			text_1 = text_dict[k_wav][0]
			wav_time = cal_wav_time(wav_path)
			t_name = k_wav.replace('.wav','.txt')

			f1 = codecs.open(t_dir_1+'/'+t_name,'w')
			
			temp_1 = json.dumps({"start_time":0,"sex":0,"end_time":wav_time,"text":text_1},sort_keys=None)
			#temp_2 = json.dumps({"start_time":0,"sex":0,"end_time":wav_time,"text":text_2},sort_keys=None)
			f1.write(temp_1)
			#f2.write(temp_2)
			f1.close()
			#f2.close()


if __name__ == '__main__':
	main()


